<template>
    <div class="mobile-code-box">
        <div class="mobile-title">
            {{ i18n('message.addUserByWxGzh', '注册用户') }}
        </div>
        <a-form-model
            ref="formRegister"
            :model="formData"
            :rules="rules"
            id="formRegister"
        >
            <a-form-model-item prop="mobile">
                <a-input
                    size="large"
                    :placeholder="i18n('message.number','11 位手机号')"
                    v-model="formData.mobile"
                >
                    <a-select slot="addonBefore" size="large" defaultValue="+86">
                        <a-select-option value="+86">+86</a-select-option>
                        <a-select-option value="+87">+87</a-select-option>
                    </a-select>
                </a-input>
            </a-form-model-item>

            <a-form-model-item prop="captcha">
                <a-input-group compact style="display: flex;">
                    <a-input
                        size="large"
                        :placeholder="i18n('message.code','验证码')"
                        v-model="formData.captcha"
                        style="flex: 1;"
                    >
                        <a-icon slot="prefix" type="mail" :style="{ color: 'rgba(0,0,0,.25)' }"/>
                    </a-input>
                    <a-button
                        size="large"
                        style="min-width: 112px"
                        :disabled="state.smsSendBtn"
                        @click.stop.prevent="getCaptcha"
                        v-text="!state.smsSendBtn && i18n('message.codeGet','获取验证码')||(state.time+' s')"></a-button>
                </a-input-group>

            </a-form-model-item>


            <a-form-model-item>
                <a-button
                    size="large"
                    type="primary"
                    htmlType="submit"
                    class="register-button"
                    :loading="registerBtn"
                    :disabled="registerBtn"
                    @click="handleSubmit"
                    style="width: 100%"
                >{{ $ti18('rxForm.okBtn', '确定') }}
                </a-button>
                <div style="text-align: right;">
                    <router-link  :to="{ name: 'login' }">
                        {{ i18n('form.account', '使用已有账户登录') }}
                    </router-link>
                </div>
            </a-form-model-item>

        </a-form-model>
    </div>
</template>

<script>
import LoginApi from '@/api/login'
import {TokenUtil} from "@lowcode/jpaas-common-lib"


export default {
    name: 'mobileCodeLogin',
    components: {

    },
    data() {
        return {
            state: {
                time: 60,
                smsSendBtn: false,
            },
            registerBtn: false,
            form: this.$form.createForm(this),
            formData: {
                mobile:'',
                captcha:'',
            },
            ticketJson: {},
            rules:{
                captcha:[
                    { required: true, message: this.i18n('message.code','验证码','input')},
                ],
                mobile:[
                    {required:true,message:this.i18n('message.mobileNumber','请输入手机号')},
                    {pattern:/^1[3-9]\d{9}$/,message:this.i18n('message.number','正确的手机号','input')}
                ]
            }
        }
    },
    computed: {},
    created() {
        this.ticketJson = this.$route.query;
    },
    methods: {
        i18n(name, text, key) {
            return this.$ti18(name, text, "viewsUser", key);
        },
        handleSubmit() {
            let self_ = this;
            this.$refs.formRegister.validate(valid => {
                if (valid) {
                    self_.ticketJson.mobile = this.formData.mobile;
                    self_.ticketJson.captcha = this.formData.captcha;

                    self_.registerBtn = true;
                    LoginApi.addWxGzhUserAndLogin(self_.ticketJson).then(res => {
                        self_.registerBtn = false;
                        if (!res.success || !res.data || !res.data.access_token) {
                            self_.$message.error(res.message);
                            return;
                        }
                        let token = res.data.access_token;
                        if (token) {
                            TokenUtil.setToken(token);
                            self_.$store.commit('SET_TOKEN', token);
                            self_.loginWxGzhSuccess();
                        }
                    }).catch(err => {
                        self_.requestFailed(err)
                    })
                } else {
                    return false;
                }
            });
        },
        //登录成功处理
        loginWxGzhSuccess() {
            this.$router.push({name: 'admin-index'}, () => {
                this.$notification.success({
                    message: this.i18n('tips.welcome','欢迎'),
                    description: `${timeFix()}，`+this.i18n('tips.welcomeBack','欢迎回来!')
                })
            })
        },
        getCaptcha(e) {
            let self = this ;
            this.$refs.formRegister.validateField(['mobile'],(res)=>{
                if(!res){
                    self.state.smsSendBtn = true
                    const interval = window.setInterval(() => {
                        if (self.state.time-- <= 0) {
                            self.state.time = 60
                            self.state.smsSendBtn = false
                            window.clearInterval(interval)
                        }
                    }, 1000)
                    const hide = self.i18n('tips.sent', '验证码发送中..');

                    LoginApi.getNewUserSmsCaptcha({mobile: self.formData.mobile}).then(res => {
                        setTimeout(hide, 500);
                        if (res.code == 200) {
                            self.$notification['success']({
                                message: self.i18n('message.tips', '提示'),
                                description: self.i18n('message.successfully', '验证码获取成功'),
                                duration: 8
                            })
                        } else {
                            self.state.smsSendBtn = false
                        }


                    }).catch(err => {
                        setTimeout(hide, 1)
                        clearInterval(interval)
                        self.state.time = 60
                        self.state.smsSendBtn = false
                        self.requestFailed(err)
                    })
                }
            })
        },
        requestFailed(err) {
            this.$notification['error']({
                message: this.$ti18('rxMsa.errorTip', '错误'),
                description: ((err.response || {}).data || {}).message || this.i18n('message.again', '错误，请稍后再试'),
                duration: 4
            })
            this.registerBtn = true
        }
    },

}
</script>
<style scoped>
.mobile-code-box >>> .ant-form-item{
    margin-bottom: 16px;
}
.mobile-title{
    text-align: center;
    padding: 10px 0 16px;
    font-size: 18px;
}
.mobile-code-box{
    background-color: #fff;
    padding: 20px;
    border-radius: 6px;
}
</style>
